package com.examination.auth.filter;

import com.examination.auth.utils.JacksonUtil;
import com.examination.auth.utils.JwtUtil;
import com.examination.auth.utils.RedisCache;
import com.examination.auth.utils.WebUtil;
import com.examination.constants.SystemConstants;
import com.examination.domain.auth.entity.LoginUser;
import com.examination.domain.common.ResponseResult;
import com.examination.enums.AppHttpCodeEnum;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = request.getHeader(SystemConstants.KEY_TOKEN);

        if (!StringUtils.hasText(token)) {
            //说明该接口不需要登录  直接放行
            filterChain.doFilter(request, response);
            return;
        }

        Claims claims = null;

        try {
            claims = JwtUtil.parseJwt(token);
        } catch (Exception e) {
            //token超时、非法——响应告诉前端需要重新登陆
            ResponseResult<?> result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtil.renderString(response, JacksonUtil.toJsonString(result));
            return;
        }

        String userId = claims.getSubject();
        //从redis获取用户信息

        LoginUser loginUser = redisCache.getCacheObject(SystemConstants.REDIS_PRE + userId);

        if (Objects.isNull(loginUser)) {
            //表明登录验证信息过期了——需要重新验证
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtil.renderString(response, JacksonUtil.toJsonString(result));
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
